package chargeservice

import (
	"admin100/app/dao/centerdao"
	"admin100/app/dao/chargedao"
	"admin100/app/dao/gamedao"
	"admin100/app/model/chargemodel"
	"admin100/app/model/gamemodel"
	"admin100/app/service/centerservice"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"strings"

	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
)

var ChargeInfoRecord = &chargeInfoRecordService{}

type chargeInfoRecordService struct {
}

//
func (s *chargeInfoRecordService) GetServerChargeCountList(platformId, serverId string, channelList []string) []gdb.Value {
	m := chargedao.ChargeInfoRecord.Fields("count(" + chargedao.ChargeInfoRecord.Columns.PlayerId + ") count").Where(
		g.Map{
			chargedao.ChargeInfoRecord.Columns.PartId:     platformId,
			chargedao.ChargeInfoRecord.Columns.ServerId:   serverId,
			chargedao.ChargeInfoRecord.Columns.ChargeType: 99,
			chargedao.ChargeInfoRecord.Columns.Channel:    channelList,
		},
	).Group(chargedao.ChargeInfoRecord.Columns.PlayerId)
	chargeTimesList, err := m.Array()
	defErr.IfPanic(err, define.DataOptFail)

	return chargeTimesList
}

//获取某天注册的玩家 该时间区间内总充值人民币
func (s *chargeInfoRecordService) GetServerTotalChargeIngot(platformId, serverId string, channelList []string) int {
	r, err := chargedao.ChargeInfoRecord.Fields(
		"sum(" + chargedao.ChargeInfoRecord.Columns.Ingot + ")").Where(g.Map{
		chargedao.ChargeInfoRecord.Columns.PartId:     platformId,
		chargedao.ChargeInfoRecord.Columns.ServerId:   serverId,
		chargedao.ChargeInfoRecord.Columns.Channel:    channelList,
		chargedao.ChargeInfoRecord.Columns.ChargeType: 99,
	}).FindValue()
	defErr.IfPanic(err, define.DataOptFail)
	if r == nil {
		return 0
	}

	return gconv.Int(r.Val())
}

//获取区服总充值人民币
func (s *chargeInfoRecordService) GetServerTotalChargeMoneyByChannelList(platformId, serverId string, channelList []string) int {
	r, err := chargedao.ChargeInfoRecord.Fields(
		"sum(" + chargedao.ChargeInfoRecord.Columns.Money + ")").Where(g.Map{
		chargedao.ChargeInfoRecord.Columns.PartId:     platformId,
		chargedao.ChargeInfoRecord.Columns.ServerId:   serverId,
		chargedao.ChargeInfoRecord.Columns.Channel:    channelList,
		chargedao.ChargeInfoRecord.Columns.ChargeType: 99,
	}).Value()
	defErr.IfPanic(err, define.DataOptFail)
	if r == nil {
		return 0
	}

	return gconv.Int(r.Val())
}

//获取区服付费人数
func (s *chargeInfoRecordService) GetServerChargePlayerCount(platformId, serverId string, channelList []string) int {
	r, err := chargedao.ChargeInfoRecord.Fields(
		"count(DISTINCT " + chargedao.ChargeInfoRecord.Columns.PlayerId + ")").Where(g.Map{
		chargedao.ChargeInfoRecord.Columns.PartId:     platformId,
		chargedao.ChargeInfoRecord.Columns.ServerId:   serverId,
		chargedao.ChargeInfoRecord.Columns.Channel:    channelList,
		chargedao.ChargeInfoRecord.Columns.ChargeType: 99,
	}).Value()
	defErr.IfPanic(err, define.DataOptFail)
	if r == nil {
		return 0
	}

	return gconv.Int(r.Val())
}

//获取区服二次付费人数
func (s *chargeInfoRecordService) GetServerSecondChargePlayerCount(platformId, serverId string, channelList []string) int {
	r, err := chargedao.ChargeInfoRecord.Fields(
		"count(DISTINCT " + chargedao.ChargeInfoRecord.Columns.PlayerId + ")").Where(g.Map{
		chargedao.ChargeInfoRecord.Columns.PartId:     platformId,
		chargedao.ChargeInfoRecord.Columns.ServerId:   serverId,
		chargedao.ChargeInfoRecord.Columns.Channel:    channelList,
		chargedao.ChargeInfoRecord.Columns.ChargeType: 99,
		chargedao.ChargeInfoRecord.Columns.IsFirst:    0,
	}).Value()
	defErr.IfPanic(err, define.DataOptFail)
	if r == nil {
		return 0
	}

	return gconv.Int(r.Val())
}

type ChargeTotalMoney struct {
	Count  int `json:"count"`
	ItemId int `json:"item_id"`
}

type ChargeInfoRecordListResponse struct {
	Data             []*chargemodel.ChargeInfoRecord
	Total            int64
	SumPlayerCount   int64
	SumMoneyCount    int64
	ChargeTotalMoney []*ChargeTotalMoney
	ExchangeRate     float32
}

// record list
func (s *chargeInfoRecordService) GetChargeInfoRecordList(req *gamemodel.ChargeInfoRecordQueryReq) ChargeInfoRecordListResponse {

	var (
		node    = centerservice.CGameServer.FetchNodeStrByPtIdAndSid(req.PlatformId, req.ServerId)
		sumData struct {
			MoneyCount  float32
			PlayerCount int64
		}
		data  = make([]*chargemodel.ChargeInfoRecord, 0)
		count int
		err   error
	)

	accIdList := make([]string, 0)
	//获以 accIdlist
	if req.Promote != "" {
		accIdList = centerdao.GlobalAccount.GetGlobalAccIdsByPromote(req.Promote)
	}

	column := chargedao.ChargeInfoRecord.Columns
	gMap := g.Map{
		column.ChargeType:      99,
		column.PlatformOrderId: req.PlatFormOrderId,
		column.PartId:          req.PlatformId,
		column.ServerId:        req.ServerId,
		column.Channel:         strings.Split(req.ChannelList, ","), // global已过滤过空格
		column.AccId:           accIdList,
	}

	m := chargedao.ChargeInfoRecord.WhereValNotEmpty(gMap)
	if req.StartTime > 0 {
		m = m.Where(column.RecordTime+" between ? and ?", g.Slice{req.StartTime, req.EndTime})
	}
	lastChargeInfoRecordModel := m.Clone()

	if err := m.Fields("sum(" +
		chargedao.ChargeInfoRecord.Columns.Money + ") as money_count, count(DISTINCT " +
		chargedao.ChargeInfoRecord.Columns.PlayerId + ") as player_count").Scan(&sumData); err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}

	// if req.Promote != "" {
	if req.StartTime > 0 {

		m = chargedao.ChargeInfoRecord.WhereValNotEmpty(g.Map{
			column.PlatformOrderId:                 req.PlatFormOrderId,
			column.PartId:                          req.PlatformId,
			column.AccId:                           req.AccId,
			column.OrderId:                         req.OrderId,
			column.PlayerId:                        req.PlayerId,
			column.ServerId:                        req.ServerId,
			column.Channel:                         strings.Split(req.ChannelList, ","),
			column.RecordTime + " between ? and ?": g.Slice{req.StartTime, req.EndTime},
			column.ChargeType:                      99,
		}).Page(req.Cur, req.PNum)
		m.M = m.M.OrderBy(column.RecordTime + " desc")
		count, err = m.Clone().Count()
		defErr.IfPanic(err, define.DataOptFail, err.Error())
		data, err = m.FindAll()
		defErr.IfPanic(err, define.DataOptFail, err.Error())

	} else {
		m = chargedao.ChargeInfoRecord.WhereValNotEmpty(g.Map{
			column.PlatformOrderId: req.PlatFormOrderId,
			column.PartId:          req.PlatformId,
			column.AccId:           req.AccId,
			column.OrderId:         req.OrderId,
			column.PlayerId:        req.PlayerId,
			column.ServerId:        req.ServerId,
			column.Channel:         strings.Split(req.ChannelList, ","),
			column.ChargeType:      99,
		}).Page(req.Cur, req.PNum)
		m.M = m.M.OrderBy(column.RecordTime + " desc")
		count, err = m.Clone().Count()
		if err != nil {
			defErr.Panic(define.DataOptFail, err.Error())
		}
		data, err = m.FindAll()
		if err != nil {
			defErr.Panic(define.DataOptFail, err.Error())
		}
	}
	// } else {
	// 	if req.StartTime > 0 {
	// todo
	// 	} else {

	// 	}
	// }

	for _, v := range data {
		pGameDb := gamedao.NewPlayerDao(node)
		v.PlayerName = pGameDb.GetPlayerName_2(req.ServerId, v.PlayerId)
		v.LastLoginTime = pGameDb.GetPlayerLastLoginTime(req.ServerId, v.PlayerId)
	}

	totalData := make([]*ChargeTotalMoney, 0)
	err = lastChargeInfoRecordModel.Fields("count(*) as count, " +
		chargedao.ChargeInfoRecord.Columns.ChargeItemId + " as item_id").Group(chargedao.ChargeInfoRecord.Columns.ChargeItemId).Scan(&totalData)
	if err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}

	var exchangeRate float32 = 1.0

	return ChargeInfoRecordListResponse{
		Data:             data,
		Total:            int64(count),
		SumPlayerCount:   sumData.PlayerCount,
		SumMoneyCount:    int64(sumData.MoneyCount),
		ChargeTotalMoney: totalData,
		ExchangeRate:     exchangeRate,
	}
}
